﻿using System;
using System.Windows.Browser;
using SilverQuery;

namespace SilverQueryDemo.jqia
{
	/// <summary>
	/// SilverQuery port of the photomatic jQuery plugin sample from the book jQuery in Action.
	/// </summary>
	public class Photomatic : SilverQueryComponent
	{
		public override void ready()
		{
			@q("#thumbnails img").photomatic(new map(){
          {"photoElement", "#photo"}, 
					{"previousControl", "#previousButton"},
					{"nextControl", "#nextButton"},
					{"firstControl", "#firstButton"},
					{"lastControl", "#lastButton"}
        });
		}
	}

	/// <summary>
	/// Static class that houses the Photomatic plugin including the extension method
	/// and a private implementation class.
	/// </summary>
	public static class PhotomaticPlugin
	{
		/// <summary>
		/// Extension method for the photomatic plugin.
		/// </summary>
		/// <param name="set"></param>
		/// <param name="properties"></param>
		/// <returns></returns>
		public static jQuery photomatic(this jQuery set, map settings)
		{
			return new Plugin().Execute(set, settings);
		}

		/// <summary>
		/// Implementation of the photomatic plugin.
		/// </summary>
		private class Plugin : SilverQueryPlugin
		{
			private map _settings;
			private jQuery _photoElement;
			private jQuery _thumbnails;
			private int _current;

			public override jQuery Execute(jQuery set, map settings)
			{
				Func<string, string> transformer = (s)=>s.Replace("thumbnail","photo");

				_settings = Utility.extend(new map(){
					{ "photoElement", "#photomaticPhoto"},
					{ "transformer", transformer},
					{ "nextControl", null},
					{ "previousControl", null},
					{ "firstControl", null},
					{ "lastControl", null}
				}, settings ?? new map());

				_photoElement = @q((string)settings["photoElement"]);

				_thumbnails = set.filter("img").each((i, elem)=> {
					@q(elem).attr("index", i.ToString());
				});

				EventCallback nextClick = (e)=> {
					showPhoto((_current+1) % _thumbnails.length);
					return false;
				};

				_photoElement.click(nextClick);	
				@q((string)_settings["nextControl"]).click(nextClick);
				@q((string)_settings["previousControl"]).click(e =>
				{
					showPhoto(_thumbnails.length + _current - 1);
					return false;
				});
				@q((string)_settings["firstControl"]).click(e =>
				{
					showPhoto(0);
					return false;
				});
				@q((string)_settings["lastControl"]).click(e =>
				{
					showPhoto(_thumbnails.length-1);
					return false;
				});
				showPhoto(0);
				return set;
			}

			private void showPhoto(int index)
			{
				var transformer = (Func<string, string>)_settings["transformer"];
				_photoElement.attr("src", transformer(@q(_thumbnails.get(index)).attr("src")));
				_current = index;
			}
		}
	}
}
